package com.zzs.client.controller;

import com.zzs.client.pojo.dto.user.PasswordLoginDTO;
import com.zzs.client.pojo.dto.user.SmsCodeLoginDTO;
import com.zzs.client.service.UserService;
import com.zzs.common.core.enums.ResponseCode;
import com.zzs.common.core.response.Result;
import com.zzs.common.core.util.ThreadLocalUtil;
import com.zzs.common.security.exception.ServiceException;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author zzs
 * @date 2025/03/24
 */
@RestController
@RequestMapping("/client/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/password/login")
    public Result<String> passwordLogin(@Valid @RequestBody PasswordLoginDTO loginDTO) {
        String token = userService.passwordLogin(loginDTO.getPhone(), loginDTO.getPassword());
        return Result.success(token);
    }

    @DeleteMapping("/logout")
    public Result<Void> logout() {
        Long userId = ThreadLocalUtil.getUserId();
        if (userId == null) {
            throw new ServiceException(ResponseCode.UNAUTHORIZED);
        }
        userService.logout(userId);
        return Result.success();
    }

    @GetMapping("/sms/login")
    public Result<Void> sendCode(@RequestParam("phone") String phone) {
        if (phone == null || phone.isBlank()) {
            return Result.error(ResponseCode.PHONE_ERROR);
        }
        phone = phone.trim();
        if (!phone.matches("^\\d{11}$")) {
            return Result.error(ResponseCode.PHONE_ERROR);
        }
        userService.sendCode(phone);
        return Result.success();
    }

    @PostMapping("/sms/login")
    public Result<String> smsCodeLogin(@Valid @RequestBody SmsCodeLoginDTO loginDTO) {
        String token = userService.smsCodeLogin(loginDTO.getPhone(), loginDTO.getSmsCode());
        return Result.success(token);
    }
}
